import "antd/lib/spin/style/css";
import _Spin from "antd/lib/spin";
import "antd/lib/select/style/css";
import _Select from "antd/lib/select";

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

/**
 *@desc
 *@author bie
 *@date [$]
 */
import React, { useCallback, useEffect, useState } from 'react';
import Icon from '@ant-design/icons';
import PropTypes from 'prop-types';
import useRequest from '../request';
import './select.less';
/**
 * 检查list中是否包含data，若不包含则加入data，默认返回list
 */

var Option = _Select.Option;
export var checkListHasData = function checkListHasData(list, key) {
  var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var filter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  var listTem = [];

  if (data[key]) {
    var isFound = false; // eslint-disable-next-line no-restricted-syntax

    var _iterator = _createForOfIteratorHelper(list),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var item = _step.value;

        if (item[key] === data[key]) {
          isFound = true;
          break;
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    if (!isFound) {
      listTem = [].concat(_toConsumableArray(list), [data]);
    } else {
      listTem = list;
    }
  } else {
    listTem = list;
  } // 过滤


  var newList = [];

  if (filter.value) {
    // eslint-disable-next-line no-restricted-syntax
    var _iterator2 = _createForOfIteratorHelper(listTem),
        _step2;

    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var _item = _step2.value;

        if (filter.value === _item[filter.key]) {
          newList.push(_item);
        }
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }
  } else {
    newList = listTem;
  }

  return newList;
};
export var getOption = function getOption(name, key, list) {
  var disabledList = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];

  if (!list || list.length === 0) {
    return [];
  }

  return list.map(function (i) {
    var querykey = i.namePinyin ? i.namePinyin + i.name : i.name; // 拼音搜索码

    return /*#__PURE__*/React.createElement(Option, {
      querykey: querykey,
      value: i[key],
      key: i[key],
      disabled: disabledList.indexOf(i[key]) > -1
    }, i[name]);
  });
};
var timer = null;

var SelectCustom = function SelectCustom(props) {
  var _useState = useState(''),
      _useState2 = _slicedToArray(_useState, 2),
      valueCurrent = _useState2[0],
      setValueCurrent = _useState2[1]; // 当前显示值


  var _useState3 = useState([]),
      _useState4 = _slicedToArray(_useState3, 2),
      optionListCurrent = _useState4[0],
      setOptionListCurrent = _useState4[1]; // 当前显示列表数据


  var _useRequest = useRequest(),
      loading = _useRequest.loading,
      postData = _useRequest.postData;

  var _props$extraObject = props.extraObject,
      extraObject = _props$extraObject === void 0 ? {} : _props$extraObject,
      _props$disabledList = props.disabledList,
      disabledList = _props$disabledList === void 0 ? [] : _props$disabledList,
      onChange = props.onChange,
      value = props.value,
      _props$optionList = props.optionList,
      optionList = _props$optionList === void 0 ? [] : _props$optionList,
      searchUrl = props.searchUrl,
      allowSearch = props.allowSearch,
      _props$keyValue = props.keyValue,
      keyValue = _props$keyValue === void 0 ? ['name', 'id'] : _props$keyValue,
      args = _objectWithoutProperties(props, ["extraObject", "disabledList", "onChange", "value", "optionList", "searchUrl", "allowSearch", "keyValue"]);

  var triggerChange = useCallback(function (valueTem) {
    // Should provide an event to pass value to Form.
    if (onChange) {
      onChange(valueTem);
    }
  }, [onChange]);
  var onSelectSearch = useCallback(function (valueTem) {
    setOptionListCurrent([]);

    if (onChange) {
      onChange(valueTem);
    }

    if (valueTem && searchUrl) {
      if (timer) {
        clearTimeout(timer);
      }

      timer = setTimeout(function () {
        postData(searchUrl, {
          data: {
            condition: {
              keyword: valueTem
            },
            pagingQuery: {
              pageIndex: 1,
              pageSize: 500
            }
          }
        }).then(function (res) {
          if (res && res.success) {
            var keys = props.keyValue || [];

            var optionListTem = _toConsumableArray(res.models).map(function (i) {
              return _objectSpread(_objectSpread({}, i), {}, {
                label: i[keys[0]],
                value: i[keys[1]]
              });
            });

            setOptionListCurrent(optionListTem);
          }
        });
      }, 800);
    }
  }, [searchUrl, onChange]); // 监听 optionList

  useEffect(function () {
    setOptionListCurrent(optionList);
  }, [optionList]); // 监听 value 变化

  useEffect(function () {
    setValueCurrent(value);
  }, [value]);
  return /*#__PURE__*/React.createElement("span", {
    className: "xuanyue-select"
  }, /*#__PURE__*/React.createElement(_Select, _extends({
    showSearch: true,
    allowClear: true // allowClear
    ,
    optionFilterProp: "children",
    showArrow: true,
    virtual: true,
    onSearch: allowSearch ? onSelectSearch : null // maxTagTextLength={4}<BulbOutlined />
    // maxTagCount={mode ? 2 : 0}
    ,
    notFoundContent: allowSearch ? loading ? /*#__PURE__*/React.createElement(_Spin, {
      size: "small"
    }) : /*#__PURE__*/React.createElement(Icon, {
      type: "bulb"
    }) : null,
    style: {
      width: '100%'
    },
    placeholder: "\u8BF7\u9009\u62E9",
    dropdownMatchSelectWidth: true,
    getPopupContainer: function getPopupContainer(trigger) {
      return trigger.parentNode;
    } // optionFilterProp="querykey"
    ,
    filterOption: allowSearch ? false : function (_input, option) {
      if (_input) {
        var curr = (option.props.querykey || option.props.children || '').toLowerCase() || '';
        var l = _input.length;
        var s = curr.substr(0, l);
        return s === _input || curr.includes(_input.toLowerCase());
      }
    }
  }, args, {
    value: valueCurrent,
    onChange: triggerChange
  }), getOption.apply(void 0, _toConsumableArray(keyValue).concat([checkListHasData(optionListCurrent, keyValue[1], extraObject), disabledList]))), args.addonAfter);
};
/*
 * 关键附加参数，其余参数 请参考 antd select组件
 * */


SelectCustom.propTypes = {
  disabledList: PropTypes.array,
  optionList: PropTypes.array,
  value: PropTypes.string,
  extraObject: PropTypes.object,
  onChange: PropTypes.func,
  searchUrl: PropTypes.string,
  allowSearch: PropTypes.bool,
  keyValue: PropTypes.array
};
export default React.memo(SelectCustom);